import os
import pathlib
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.font_manager import FontProperties
from collections import OrderedDict

plt.rcParams.update({'figure.max_open_warning': 0})

font = FontProperties(fname='/Library/Fonts/Songti.ttc')
sulv = OrderedDict()
xiachenliang = OrderedDict()


def get_files():
    dates = []
    p = pathlib.Path('data')
    for file in p.iterdir():
        file_name = os.path.basename(file)
        file_name_prefix = file_name.split('.')[0]
        dates.append(file_name_prefix)
    return dates


dates = get_files()


def get_vp():
    """
    轮训所有的csv文件
    :return: 所有的观察点名称
    """
    s = set()
    for d in dates:
        with open("data/{}.csv".format(d), encoding='gbk') as f:
            lines = f.readlines()
            for line in lines[2:]:
                data = line.split(',')
                s.add(data[0])
    return s


def init_struct():
    """
    构建用于存放此时间段内，所有观察点的速率和下沉量数据结构
    """
    for view_point in get_vp():
        sulv[view_point] = []
        xiachenliang[view_point] = []


init_struct()

"""
轮训所有csv文件， 当天有观察点数据的，就插入数据，如果没有，就插入0， 这是为了之后画图
"""
for d in dates:
    with open("data/{}.csv".format(d), encoding='gbk') as f:
        cur_set = set()
        lines = f.readlines()
        for line in lines[2:]:
            data = line.split(',')
            view_point = data[0].strip()
            d_sulv = abs(float(data[4]))    # 由字符串转换为float, 取得绝对值
            d_xiachen = abs(float(data[5]))
            cur_set.add(view_point)

            sulv[view_point].append(d_sulv)
            xiachenliang[view_point].append(d_xiachen)

        """
        当天没有数据的观测点，速率和下沉量都为0
        """
        for view_point in (get_vp() - cur_set):
            sulv[view_point].append(0)
            xiachenliang[view_point].append(0)


for view_point in get_vp():
    fig = plt.figure(figsize=(8, 6), dpi=120)
    ax1 = fig.add_subplot(111)

    xs = [datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
    ax1.set_ylabel('沉降量', fontproperties=font)
    plt.xticks(rotation=30)

    ax2 = ax1.twinx()
    ax2.set_ylabel('速率', fontproperties=font)
    ax1.plot(xs, xiachenliang[view_point], '-', label=view_point)
    ax2.plot(xs, sulv[view_point], '-r', linestyle='--', label=view_point)

    ax1.set_ylim([0, max(xiachenliang[view_point]) + 0.2])
    ax2.set_ylim([0, max(sulv[view_point]) + 0.2])

    ax1.legend(loc=2)
    ax2.legend(loc=1)
    plt.title("{}: 速率与沉降量的关系".format(view_point), fontproperties=font)
    fig.savefig("results/{}.png".format(view_point))
